Skip to main content

Chapter 18 - Conditional Expressions

Conditional expressions (condition ? true: false)

Create TF Configs


https://developer.hashicorp.com/terraform/language/expressions/conditionals

A Conditional Expressions looks like this: condition ? true_val : false_val It can be read as "Choose the true_val or the false_val dependent on the result of the condition." The local variables are defined as follows:

vnet_address_space = (var.environment == "dev" ? var.vnet_address_space_dev : var.vnet_address_space_all)

The variables.tf file contains:

# Virtual Network Address - Dev
variable "vnet_address_space_dev" {
description = "Virtual Network Address Space for Dev Environment"
type = list(string)
default = [ "10.0.0.0/16" ]
}

# Virtual Network Address -
variable "vnet_address_space_all" {
description = "Virtual Network Address Space for All Environments except dev"
type = list(string)
default = [ "10.1.0.0/16", "10.2.0.0/16", "10.3.0.0/16" ]
}

The resource looks like normal:

resource "azurerm_virtual_network" "myvnet" {
#name = "${var.business_unit}-${var.environment}-${var.virtual_network_name}"
name = local.vnet_name
#address_space = ["10.0.0.0/16"]
address_space = local.vnet_address_space
location = azurerm_resource_group.myrg.location
resource_group_name = azurerm_resource_group.myrg.name
tags = local.common_tags
}

From the documentation: A common use of conditional expressions is to define defaults to replace invalid values:

var.a != "" ? var.a : "default-a"

If var.a is an empty string then the result is "default-a", but otherwise it is the actual value of var.a.

Conditions inside of a resource


Another thing we can do is do inside of a resource:

resource "azurerm_virtual_network" "myvnet" {
#count = 2
count = var.environment == "dev" ? 1 : 5